package com.motu.monstercity.server.game.web;


import com.motu.monstercity.module.common.utility.EventBusConstant;
import com.motu.vertx.module.utility.base.ServerOpenBase;
import com.motu.vertx.module.utility.base.ServerOpenInterFace;
import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class ServerOpenManager extends ServerOpenBase implements ServerOpenInterFace {
	private static Logger logger = LoggerFactory.getLogger(ServerOpenManager.class);

	// 初始化
	public static void init(Vertx vertx) {
		ServerOpenBase.init(vertx);
		ServerOpenBase.serverOpenInterFace = new ServerOpenManager();
		ServerOpenBase.gmAdress = EventBusConstant.getAddress(EventBusConstant.GAME_GM);
	}

	/**
	 * 执行开服逻辑, 该方法各个项目需要重写，server_info表会有差异，有些项目需要重载活动等
	 * @param curServerId 当前的服务器id
	 * @param serverNum 开服数量
	 * @param openType 开服类型，自动开服，立即开服，预约开服
	 * @param operator 操作者
	 */
	public void doOpenServer(int serverNum, int openType, String operator) {
		int curServerId = Future.await(ServerOpenBase.getLastServerId());
		logger.info("###doOpenServer serverid:" + curServerId + " num:" + serverNum + " openType:" + openType);
		int flag = Future.await(updateOldServer());
		if (flag != 0) {
			return;
		}
		flag = Future.await(insertIntoServerInfo(curServerId, serverNum));
		if (flag != 0) {
			return;
		}

		handleReloadServer();// 重载服务器 延迟3秒后重载服务器

		ServerOpenBase.handleOpenServerFinish(curServerId, serverNum, openType, operator);// 自动开服完成后需要处理的逻辑，更新下次开服的最小时间，发放飞书消息,记录操作日志
	}

	// 重载服务器 延迟3秒后重载服务器
	public static void handleReloadServer() {
		getVertxInstance().setTimer(3*1000l, handler->{
			GamehttpgmHandler.publishReloadServerList();
		});
	}

	// 修改原有的所有服务器状态
	public static Future<Integer> updateOldServer() {
		Promise promise = Promise.promise();
		String sql = "UPDATE server_info SET server_status = ?, is_default = ? WHERE server_status = ? OR server_id = (SELECT max_id FROM (SELECT MAX(server_id) AS max_id FROM server_info) AS tmp);";
		JsonArray params = new JsonArray();
		params.add(0);//0-火爆,2-新服
		params.add(0);//改成非推荐服
		params.add(2);// 把所有的新服 状态改成火爆
		MysqlTool.updateToDb(MysqlClient.getServerPool(), sql, params, handler-> {
			if (handler.succeeded()) {
				promise.complete(0);
			} else {
				promise.complete(1);
				logger.error(handler.cause().getMessage());
			}
		});
		return promise.future();
	}

	// 往server_info写入数据
	public static Future<Integer> insertIntoServerInfo(int curServerId, int serverNum) {
		Promise promise = Promise.promise();

		long curTime = TimeUtils.getStartTimeOfDay(TimeUtils.getCurTime());//今天的0点0分
		String sql = "insert into server_info (server_id,server_name,server_status,is_default,is_world_chat,is_merged,server_group,start_time,act_start_time,des) values ";
		JsonArray params = new JsonArray();
		int newserverid;
		for (int i=0; i<serverNum; i++) {
			newserverid = curServerId + 1 + i; // 新服的服务器id
			sql += "(?,?,?,?,?,?,?,?,?,?)";
			if (i < serverNum - 1) {
				sql += ",";
			}
			params.add(newserverid);
			params.add(getServerConfig().getServerName(newserverid));//服务器名称
			params.add(2);//0-火爆,2-新服
			params.add(1);//新服设为推荐服
			params.add(1);//是否开启跨服聊天
			params.add(0);//是否合服
			params.add(getServerConfig().getServerGroup());//服务器分组
			params.add(curTime);
			params.add(curTime);
			params.add(getServerConfig().getDes());
		}
		MysqlTool.insertAndGetID(MysqlClient.getServerPool(), sql, params, handler->{
			if (handler.succeeded()) {
				promise.complete(0);
			} else {
				promise.complete(1);
				logger.error(handler.cause().getMessage());
			}
		});
		return promise.future();
	}
}
